import {
  Card,
  Space,
  Popconfirm,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Checkbox,
  Modal,
  Empty,
  Pagination,
  Image,
  message,
} from 'antd';
import dayjs from 'dayjs';
import React, { Fragment, useState } from 'react';

import commonService from '@/api/services/commonService';
import { PayModal } from '@/components/PayModal';
import { useCommon } from '@/hooks/common';
import { toYuan } from '@/utils/format-number';

import DetailModal from './detail';
import './index.css';

import { NAV_WIDTH } from '@/layouts/dashboard/config';

const { RangePicker } = DatePicker;

const statusMap: any = {
  0: '待付款',
  1: '待发货',
  8: '待收货',
  9: '已关闭',
};

const statusOptions: any = Object.keys(statusMap).map((key) => {
  return { label: statusMap[key], value: key };
});

export default function OrderPage() {
  const uri = 'order';
  const {
    data = [],
    refetch,
    query,
    setQuery,
    searchForm,
    onSearchFormReset,
    onSearch,
    handleChange,
    doDel,
  } = useCommon({ orderNumber: '', status: '', startTime: '', endTime: '' }, uri, {
    des: '',
    id: 0,
    code: '',
    expireTime: '',
    sort: 1,
    status: '',
    fullMoney: '',
    money: '',
  });

  const [showDetail, setShowDetail] = useState(false);
  const [detail, setDetail] = useState<any>({});
  const [show, setShow] = useState<boolean>(false);
  const [payData, setPayData] = useState<any>({});
  const [checked, setChecked] = useState<any>([]);
  const [isCheckAll, setIsCheckAll] = useState<boolean>(false);

  const handleBatchPay = () => {
    if (!checked.length) {
      message.error('请选择订单！');
    }
    setPayData({ orderNumber: checked.map((item: any) => item.orderNumber)?.join(',') });
    setShow(true);
  };

  const handleBatchDelete = () => {
    if (!checked.length) {
      message.error('请选择订单！');
    }
    const ids = checked.map((item: any) => {
      return item.id;
    });
    Modal.confirm({
      title: '确定删除勾选的订单吗？',
      centered: true,
      onOk() {
        doDel(ids.join(','));
      },
    });
  };

  const toDetail = (orderNumber: string) => {
    commonService.getCustomApi('/member/order/detail', { orderNumber }).then((res) => {
      setDetail(res);
      setShowDetail(true);
    });
  };

  const handleOk = () => {
    setShow(false);
    refetch();
  };

  const toPay = (row: any) => {
    setPayData(row);
    setShow(true);
  };

  const handlePicker = (e: any) => {
    if (e) {
      setQuery({
        ...query,
        startTime: dayjs(e[0]).format('YYYY-MM-DD'),
        endTime: dayjs(e[1]).format('YYYY-MM-DD'),
      });
    } else {
      setQuery({
        ...query,
        startTime: null,
        endTime: null,
      });
    }
    console.log(query, 33333);
  };

  const handleCheckAll = (e: any) => {
    setIsCheckAll(e.target.checked);
    setChecked(e.target.checked ? data.list : []);
  };

  const onCheckboxChange = (e: any, record: any) => {
    const list = e.target.checked
      ? [...checked, record]
      : checked.filter((item: any) => item.id !== record.id);
    setIsCheckAll(list.length === data.list.length);
    setChecked(list);
  };

  const getTotal = () => {
    let total = 0;
    data.list.forEach((item: any) => {
      const num = item.detailList.reduce((acc: any, cur: any) => acc + cur.num, 0);
      total += num;
    });
    return total;
  };

  return (
    <Space direction="vertical" size="large" className="w-full pb-[120px]">
      <Card title="我的订单" bordered={false}>
        <Form layout="inline" form={searchForm} onFinish={onSearch}>
          <Form.Item name="orderNumber">
            <Input placeholder="订单号、第三方订单" />
          </Form.Item>
          <Form.Item name="status">
            <Select className="w-[160px]" options={statusOptions} placeholder="订单状态" />
          </Form.Item>
          <Form.Item>
            <RangePicker onChange={handlePicker} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={onSearchFormReset}>重置</Button>
          </Form.Item>
        </Form>
        {data.list?.length ? (
          <div className="custom-table-page">
            <div className="table-header">
              <Checkbox checked={isCheckAll} onChange={handleCheckAll} style={{ width: '30px' }} />
              <div className="flex-2">商品</div>
              <div className="flex-1" style={{ textAlign: 'center' }}>
                数量
              </div>
              <div className="flex-1">单价</div>
              <div className="flex-2">实付款</div>
              <div className="flex-1">交易状态</div>
              <div className="flex-1 text-right">交易操作</div>
            </div>
            <div className="table-body">
              {data.list.map((record: any) => (
                <div className="table-body-item">
                  <div className="table-body-item-top">
                    <div className="flex items-center">
                      <Checkbox
                        checked={checked.some((item: any) => item.id === record.id)}
                        onChange={(e) => onCheckboxChange(e, record)}
                      />
                      <div className="ml-[40px]">订单编号：{record?.orderNumber}</div>
                    </div>
                    <div>
                      总计：
                      {toYuan(
                        (record?.finalPrice || 0) +
                          (record?.freight || 0) +
                          (record?.packageFee || 0),
                      )}
                    </div>
                  </div>
                  <div className="table-body-item-content">
                    <div className="w-[30px]" />
                    <div className="flex-2 flex flex-col gap-[10px]">
                      {record.detailList.map((item: any) => {
                        return (
                          <div className="flex items-center gap-[10px]" key={item.id}>
                            {JSON.parse(item.thumbnail || '[]')?.map((item: any) => (
                              <div className="h-[80px] w-[80px]">
                                <Image alt={item.title} src={item} />
                              </div>
                            ))}
                            <div className="flex flex-col">
                              <div>{item.title}</div>
                              <div className="text-[#686B73]">编码：{item.fpId}</div>
                              <div className="text-[#686B73]">颜色：{item.color}</div>
                              <div className="text-[#686B73]">尺码：{item.size}</div>
                              <div className="text-[#686B73]">数量：{item.num}</div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                    <div className="flex-1">
                      {record.detailList.map((item: any) => {
                        return (
                          <div className="flex h-[50%] items-center justify-center">{item.num}</div>
                        );
                      })}
                    </div>
                    <div className="flex-1">{toYuan(record.totalPrice)}</div>
                    <div className="flex-2 flex flex-col">
                      <div>平台原价：{toYuan(record.totalPrice)}</div>
                      <div>优惠：{toYuan(record.couponMoney)}</div>
                      <div>优惠后：{toYuan(record.price)}</div>
                      <b>总金额：{toYuan(record.finalPrice)}</b>
                      <div>邮费：{toYuan(record.freight)}</div>
                      <div>包装费：{toYuan(record.packageFee)}</div>
                    </div>
                    <div className="flex flex-1 flex-col">
                      <div>{statusMap[Number(record.status)]}</div>
                      {record.expressNo ? <div>快递单号：{record.expressNo}</div> : ''}
                    </div>
                    <div className="flex w-full flex-1 flex-col items-end justify-center gap-[10px] text-gray">
                      {record.status === 0 ? (
                        <>
                          <Button
                            size="large"
                            className="w-[82px]"
                            type="primary"
                            onClick={() => toPay(record)}
                          >
                            付款
                          </Button>
                          <Popconfirm
                            title="确认删除该数据？"
                            okText="确定"
                            cancelText="取消"
                            placement="left"
                            onConfirm={() => doDel(record.id)}
                          >
                            <Button size="large" className="w-[82px]" type="primary" ghost danger>
                              删除订单
                            </Button>
                          </Popconfirm>
                        </>
                      ) : (
                        ''
                      )}
                      <Button
                        size="large"
                        className="w-[82px]"
                        onClick={() => toDetail(record.orderNumber)}
                      >
                        详情
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="flex-1">
            <Empty />
          </div>
        )}
        <div className="mt-[40px] flex" style={{ justifyContent: 'flex-end' }}>
          <Pagination
            total={data.totalCount}
            current={data.pageNo}
            pageSize={data.pageSize}
            onChange={(page, pageSize) => setQuery({ ...query, pageNo: page, pageSize })}
          />
        </div>
        <div
          className="bg fixed bottom-0 right-[0] flex h-[120px]  justify-between bg-[#ffffff] pl-[60px]"
          style={{
            boxShadow: 'inset 0px 1px 0px 0px #00000026,0px -4px 8px 0px #0000000C',
            left: `calc(50vw - 712px + ${NAV_WIDTH}px)`,
            paddingRight: 'calc(50vw - 712px)',
          }}
        >
          <div className="flex items-center gap-[20px]">
            <Checkbox checked={isCheckAll} onChange={handleCheckAll}>
              全选
            </Checkbox>
            <Button onClick={handleBatchDelete}>删除订单</Button>
          </div>
          <div className="flex items-center gap-[20px]">
            <div>
              数量合计：
              {(checked || []).reduce((total: number, item: any) => {
                const itemTotal = (item.detailList ?? []).reduce(
                  (acc: number, detail: any) => acc + detail.num,
                  0,
                );
                return total + itemTotal;
              }, 0)}
            </div>
            <div>
              金额：￥
              {checked
                .reduce((total: number, value: any) => {
                  return total + (value.finalPrice + value.freight + value.packageFee) / 100;
                }, 0)
                .toFixed(2) || 0}
            </div>
            <div>
              <Button type="primary" onClick={handleBatchPay} disabled={!checked.length}>
                确认付款
              </Button>
            </div>
          </div>
        </div>
      </Card>
      <PayModal
        show={show}
        orderNumber={payData.orderNumber}
        onOk={handleOk}
        onClose={() => setShow(false)}
      />
      <DetailModal
        onOk={() => setShowDetail(false)}
        onCancel={() => setShowDetail(false)}
        showDetail={showDetail}
        detail={detail}
      />
    </Space>
  );
}
